package com.maxus.mini.data.provider.characters;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.maux.mini.data.api.characters.CharactersService;
import com.maxus.mini.common.ElumClass.EntityState;
import com.maxus.mini.common.utils.BeanUtilsExtended;
import com.maxus.mini.common.PageImplE;
import com.maxus.mini.data.provider.BaseServiceImpl;
import com.maxus.mini.entity.characters.Characters;
import com.maxus.mini.entity.user.User;
import com.maxus.mini.entity.vo.characters.CharactersVo;
import com.maxus.mini.repository.characters.CharactersRepository;

/**
 * 大字
 * 
 * @author wujinsong
 *
 */
@Component()
@Service(version = "1.0.0")
public class CharactersServiceImpl extends BaseServiceImpl<Characters, Serializable> implements CharactersService<Characters, Serializable> {
	@Autowired
	private CharactersRepository<Characters> favRepository;

	@Override
	public PageImplE<Characters> page(final CharactersVo vo) {
		Page<Characters> page = favRepository.findAll(new Specification<Characters>() {

			@Override
			public Predicate toPredicate(Root<Characters> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				list.add(cb.equal(root.<String>get("entityState"), EntityState.N.name()));

				if (vo.getUserId() != null) {
					list.add(cb.equal(root.<User>get("user").<Long>get("id"), vo.getUserId()));
				}
				
				if (!StringUtils.isEmpty(vo.getQ())) {
					Predicate predicate = cb.like(root.<User>get("user").<String>get("nickname"), "%" + vo.getQ() + "%");
					Predicate predicate2 = cb.like(root.<User>get("user").<String>get("openid"), "%" + vo.getQ() + "%");
					Predicate predicate3 = cb.or(predicate, predicate2);
					
					list.add(predicate3);
				}

				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		}, vo);

		PageImplE<Characters> pageImplE = new PageImplE<>();
		BeanUtilsExtended.copyProperties(pageImplE, page);

		return pageImplE;
	}
}
